package com.storebits.testsystem.views;

import com.storebits.testsystem.*;
import com.storebits.testsystem.views.util.JsfUtil;
import com.storebits.testsystem.views.util.PaginationHelper;
import com.storebits.testsystem.beans.HotelreservationFacade;
import com.storebits.testsystem.beans.RoomFacade;
import com.storebits.testsystem.beans.UsersFacade;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.Query;
import org.primefaces.event.DateSelectEvent;

@ManagedBean(name = "hotelreservationController")
@SessionScoped
public class HotelreservationController implements Serializable {

    private Hotelreservation current;
    private DataModel items = null;
    @EJB
    private HotelreservationFacade ejbFacade;
    @EJB
    private UsersFacade userFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private List<Room> availableRooms = new ArrayList();
    private List<String> selectedRooms = new ArrayList<String>();

    public HotelreservationController() {
    }

    public Hotelreservation getSelected() {
        if (current == null) {
            current = new Hotelreservation();
            selectedItemIndex = -1;
        }
        return current;
    }

    private HotelreservationFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Hotelreservation) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Hotelreservation();
        availableRooms = new ArrayList<Room>();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            String currUsername = context.getExternalContext().getRemoteUser();
            Users reservationCustomer = userFacade.find(currUsername);
            current.setCustomer(reservationCustomer);
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("HotelreservationCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Hotelreservation) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("HotelreservationUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Hotelreservation) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("HotelreservationDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public void roomsAvailableSelectOne() {

        Query queryHotelRooms = ejbFacade.getEntityManager().
                createNativeQuery("SELECT * FROM Room WHERE hotel = #hotelId",
                Room.class);
        queryHotelRooms.setParameter("hotelId", current.getHotel().getIdHotel());
        availableRooms = queryHotelRooms.getResultList();
        System.out.println("rooms: " + availableRooms);
    }

    public List<SelectItem> getRoomsAvailableSelectOne() {
        List<SelectItem> roomItems = new ArrayList<SelectItem>();

        for (Room room : availableRooms) {
            int roomNumber = room.getRoomPK().getRoomNumber();
            roomItems.add(new SelectItem(roomNumber, room.toString()));

        }

        return roomItems;
    }

    public void updateTotalSum() {
        Hotel selectedHotel = getSelected().getHotel();
        if (selectedHotel == null) {
            return;
        }
        double totalSumForADay = 0;

        List<String> roomIds = selectedRooms;
        System.out.println("roomIds: " + roomIds);
        if (roomIds == null) {
            return;
        }

        for (String roomNumber : roomIds) {

            Query queryHotelRooms = ejbFacade.getEntityManager().
                    createNativeQuery("SELECT * FROM Room WHERE hotel = #hotelId and roomNumber = #roomNumber",
                    Room.class);
            queryHotelRooms.setParameter("hotelId", current.getHotel().getIdHotel());
            queryHotelRooms.setParameter("roomNumber", roomNumber);
            Room room = (Room) queryHotelRooms.getResultList().get(0);

            totalSumForADay += room.getPrice().doubleValue();
        }

        long numberOfDays = JsfUtil.dateDiff(current.getStartDate(),
                current.getEndDate());

        double totalSum = totalSumForADay * numberOfDays;
        double deposit = totalSum * 0.1;
        System.out.println("totalSum: " + totalSum);
        System.out.println("deposit: " + deposit);

        getSelected().setDeposit(new BigDecimal(deposit));
        getSelected().setTotalSum(new BigDecimal(totalSum - deposit));
    }

    public void handleDateSelectEndDate(DateSelectEvent event) {
        getSelected().setEndDate(event.getDate());
        updateTotalSum();
    }

    public void handleDateSelectStartDate(DateSelectEvent event) {
        getSelected().setStartDate(event.getDate());
        updateTotalSum();
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex;
    }

    public List<String> getSelectedRooms() {
        return selectedRooms;
    }

    public void setSelectedRooms(List<String> selectedRooms) {
        this.selectedRooms = selectedRooms;
    }
    
    

    @FacesConverter(forClass = Hotelreservation.class)
    public static class HotelreservationControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            HotelreservationController controller = (HotelreservationController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "hotelreservationController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Hotelreservation) {
                Hotelreservation o = (Hotelreservation) object;
                return getStringKey(o.getIdHotelReservation());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + HotelreservationController.class.getName());
            }
        }
    }
}
